package com.xiaoma.mvi.func

import android.view.animation.AccelerateInterpolator
import android.view.animation.Interpolator
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flow

fun animFlow(
    start: Float = 0F,
    end: Float = 1F,
    duration: Long = 300L,
    refreshStep: Long = 16L,
    interpolator: Interpolator = AccelerateInterpolator(),
) = when (start == end) {
    true -> emptyFlow()
    false -> flow {
        val startTime = System.currentTimeMillis()
        val totalDistance = (end - start)

        while (true) {
            val currentTime = System.currentTimeMillis()
            val intervalTime = (currentTime - startTime)
            val timePercent = (intervalTime.toFloat() / duration)

            val distancePercent = interpolator.getInterpolation(timePercent)
            val valueOffset = (totalDistance * distancePercent)
            val value = (start + valueOffset)

            if (intervalTime < duration) {
                emit(value)
                val remain = (duration - intervalTime)
                val delay = remain.coerceAtMost(refreshStep)
                delay(delay)
            } else break
        }
        emit(end)
    }
}



